package com.apestech.api.condition.conlib;

import com.apestech.api.tables.TableExec;
import com.apestech.api.tables.modul.SeqField;
import com.apestech.framework.xml.condition.modul.Condition;
import com.apestech.framework.xml.table.modul.Tables;

public class ConCreate extends ConPub {

    public ConCreate(Condition condition) throws Exception {
        super(condition);
    }

    public void addCreateTable() throws Exception {
        for(int i=0; i<super.getTableSize(); i++){
            Tables tab=super.getTables().get(i);
            if(!super.getSession().tableExists(tab.getMasterTableId())){
                createTable(tab);
            }
        }
    }

    public void createTable(boolean bdrop) throws Exception {
        for(int i=0; i<super.getTableSize(); i++){
            Tables tab=super.getTables().get(i);
            try{
                createTable(tab, bdrop);
            } catch (Exception e){
                if(e.getMessage().indexOf("建表")<0){
                    throw e;
                }
            }
        }
    }

    public void createTableSql() throws Exception {
        for(int i=0; i<super.getTableSize(); i++){
            Tables tab=super.getTables().get(i);
            createTable(tab, false, false);
        }
    }

    public void createTable(Tables tab, boolean bdrop) throws Exception {
        createTable(tab, true, bdrop);
    }

    public void createTable(Tables tab) throws Exception {
        createTable(tab, true, false);
    }

    public void createTableSql(Tables tab) throws Exception {
        createTable(tab, false);
    }

    private void createTable(Tables tab, boolean bexec, boolean bdrop) throws Exception {
        TableExec table=new TableExec(super.getSession(), tab);
        String tabname=tab.getMasterTableId();
        super.getCondition().getTableKey().getKeyValue(super.getCondition().getDimension().get(tab.getIndex()).getId());
        String prefix=super.getCondition().getTableKey().getPrefix();
        String suffix=super.getCondition().getTableKey().getSuffix();
        SeqField seqField=new SeqField();
        seqField.setPadding(6);
        seqField.setPrefix(prefix);
        if(suffix!=null) seqField.setSuffix(suffix);
        seqField.setTableId(tabname);
        seqField.setTableName(super.getSession().getForJSON().getTabComment(tabname));
        table.setSeqField(seqField);
        if(bexec){
            table.createTable(bdrop);
        } else {
            table.createTableSql();
        }
    }
}
